package com.financing.wap.web.controller.api;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.FpFundAwkwardnessDTO;
import com.financing.wap.dto.FpFundBuynoticeDTO;
import com.financing.wap.dto.FpFundCompanyDTO;
import com.financing.wap.dto.FpFundInfoDTO;
import com.financing.wap.dto.FpFundManagerDTO;
import com.financing.wap.dto.FpShopperProductDTO;
import com.financing.wap.dto.HS300DTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpFundAwkwardnessService;
import com.financing.wap.service.IFpFundBuynoticeService;
import com.financing.wap.service.IFpFundCompanyService;
import com.financing.wap.service.IFpFundInfoService;
import com.financing.wap.service.IFpFundManagerService;
import com.financing.wap.service.IFpShopperProductService;
import com.financing.wap.service.IHS300Service;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

/**
 * @Description: Controller
 * @author caojiayao
 * @version 1.0
 * @created 
 */
@Controller
@RequestMapping("/api/fund")
@Scope("prototype")
public class FpFundInfoAction  extends BaseController {
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	@Autowired
	private IFpFundCompanyService fpFundCompanyService;
	
	@Autowired
	private IFpFundManagerService fpFundManagerService;
	
	@Autowired
	private IHS300Service hs300Service;
	
	@Autowired
	private IFpFundAwkwardnessService fundAwkwardnessService;
	
	@Autowired
	private IFpFundBuynoticeService fpFundBuynoticeService;
	
	@Autowired
	private IFpShopperProductService fpShopperProductService;
	
	@RequestMapping("/fpFundInfoQueryList")
	@ResponseBody
	public ResultMap queryList(HttpServletRequest request,
			HttpServletResponse response,FpFundInfoDTO dto,Pager pager) {
		ResultMap resultMap = new ResultMap();
		try{
			log.info("Begin query fa user list!");
			
			dto.setBegin(pager.getStartIndex());
			dto.setPageSize(pager.getPageSize());
			//店铺商品查询    直接新增返回是否添加标识
			UserDTO user = getSession(true).getUser();
			if(user==null){
				user = new UserDTO();
			}
			String flagShopQuery = request.getParameter("flagShopQuery");
			String userId = user.getId();
			if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
				if(userId==null){
					resultMap.setStatus(ResultMap.STATUS.NEED_LOGIN);
					resultMap.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
					return resultMap;
				}
			}
			int count = fpFundInfoService.countFpFundInfo(dto);
			pager.setTotalCount(count);
			List<FpFundInfoDTO> list = fpFundInfoService.listFpFundInfo(dto);
			if(!StringUtil.isNullOrEmptyNStr(flagShopQuery)){
				//查询当前用户的所有标识
				fpShopperProductService.queryFlagShopFund(userId, list);
			}
			
			FpFundInfoDTO countFpFundInfoByzt = fpFundInfoService.countFpFundInfoByzt();
			resultMap.setAttribute("count", countFpFundInfoByzt);
			resultMap.setAttribute("list",list);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			
			log.info("End querylist!");
		}catch(Exception e){
			log.error("queryList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		resultMap.setAttribute("className", FpFundInfoAction.class.getName());
		resultMap.setAttribute("methodName", "list");
		return resultMap;
	}
	/** 放射 app　过滤数据
	 * @param json
	 * @return
	 */
	public String applist(String jsons){
		try {
			JSONObject json = JSON.parseObject(jsons);
			
			//获取  类名 方法名  进行放射
			JSONObject response=json.getJSONObject("attributes");
			JSONArray listArray = response.getJSONArray("list");
			for (int i = 0; i < listArray.size(); i++) {
				JSONObject jo = (JSONObject) listArray.get(i);
				//进行 多余字段过滤的数据
				jo.remove("createDate");
				jo.remove("createBy");
				jo.remove("updateDate");
				jo.remove("updateBy");
				jo.remove("jjclsj");
				jo.remove("jgxs");
				jo.remove("zzxs");
				jo.remove("jjfxr");
				jo.remove("tgyh");
				jo.remove("gzr");
				jo.remove("jjzt");
				jo.remove("jjgs");
				jo.remove("bz");
				jo.remove("fbq");
				jo.remove("bah");
				jo.remove("cpqxsm");
				jo.remove("jjjljs");
				jo.remove("jjgsbm");
				jo.remove("jjgsmc");
				jo.remove("zdrgje");
			}
			return json.toJSONString();
		} catch (Exception e) {
			log.error("error  fundinfo APPlist:",e);
			return jsons;
		}
	}
	/** 放射 wap　过滤数据
	 * @param json
	 * @return
	 */
	public String waplist(String jsons){
		try {
			JSONObject json = JSON.parseObject(jsons);
			
			//获取  类名 方法名  进行放射
			JSONObject response=json.getJSONObject("attributes");
			JSONArray listArray = response.getJSONArray("list");
			for (int i = 0; i < listArray.size(); i++) {
				JSONObject jo = (JSONObject) listArray.get(i);
				//进行 多余字段过滤的数据
				jo.remove("createDate");
				jo.remove("createBy");
				jo.remove("updateDate");
				jo.remove("updateBy");
				jo.remove("jjclsj");
				jo.remove("jgxs");
				jo.remove("zzxs");
				jo.remove("jjfxr");
				jo.remove("gzr");
				jo.remove("jjzt");
				jo.remove("jjgs");
				jo.remove("bz");
				jo.remove("fbq");
				jo.remove("bah");
				jo.remove("cpqxsm");
				jo.remove("jjjljs");
				jo.remove("jjgsbm");
				jo.remove("jjgsmc");
				jo.remove("zdrgje");
			}
			return json.toJSONString();
		} catch (Exception e) {
			log.error("error  fundinfo WAPlist:",e);
			return jsons;
		}
	}
	@RequestMapping("/fpFundInfoDetail")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request,
			HttpServletResponse response, FpFundInfoDTO requestDto) {
		ResultMap resultMap = new ResultMap();
		try{
			FpFundInfoDTO dto = fpFundInfoService.getFpFundInfo(requestDto.getId());
			
			if(dto!=null && !dto.getPubStatus().equals("1")){
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultMap.STATUS_CODE_FUND_INFO_NOTPUB_ERROR);
				return resultMap;
			}
			
			//基金公司
			FpFundCompanyDTO companyDTO = new FpFundCompanyDTO();
			//重仓股
			List<FpFundAwkwardnessDTO> awkwardnessList = new ArrayList<FpFundAwkwardnessDTO>();
			//购买须知
			FpFundBuynoticeDTO buynoticeDTO = new FpFundBuynoticeDTO();
			//基金经理人
			List<FpFundManagerDTO> managerList = new ArrayList<FpFundManagerDTO>();
			
			if(dto != null && !StringUtil.isNullOrEmptyStr(dto.getJjbm())){
				//基金公司
				List<FpFundCompanyDTO> companyDTOs = fpFundCompanyService.getFpFundCompanyByFundId(dto.getJjbm());
				if(companyDTOs != null && !companyDTOs.isEmpty()){
					companyDTO = companyDTOs.get(0);
					
					//基金总数和基金经理总数
					if(companyDTO != null && !StringUtil.isNullOrEmptyStr(companyDTO.getJjgsbm())){
						//公司旗下基金
						List<FpFundInfoDTO> funds = new ArrayList<FpFundInfoDTO>();
						//旗下基金经理
						List<FpFundManagerDTO> managers = new ArrayList<FpFundManagerDTO>();
						funds = fpFundInfoService.listFpFundInfoByCompanyId(companyDTO.getJjgsbm());
						managers = fpFundManagerService.listFpFundManagerByCompanyId(companyDTO.getJjgsbm());
						if(funds!=null){
							companyDTO.setFundCount(funds.size());
						}
						if(managers != null){
							companyDTO.setManagerCount(managers.size());
						}
					}
				}
				//基金经理
				managerList = fpFundManagerService.listFpFundManagerByFundId(dto.getJjbm());
				//重仓股
				FpFundAwkwardnessDTO awkwardnessDTO = new FpFundAwkwardnessDTO();
				awkwardnessDTO.setJjbm(dto.getJjbm());
				awkwardnessList = fundAwkwardnessService.listFpFundAwkwardnessByFundId(awkwardnessDTO);
				//购买须知
				buynoticeDTO = new FpFundBuynoticeDTO();
				buynoticeDTO.setJjbm(dto.getJjbm());
				buynoticeDTO = fpFundBuynoticeService.getFpFundBuynotice(buynoticeDTO);
			}
			
			//产品其他信息fp_shopper_product
			UserDTO user=SessionUtil.getSession(true).getUser();
			if(dto !=null && user != null) {
				FpShopperProductDTO  fsp = new FpShopperProductDTO();
				fsp.setProductId(String.valueOf(dto.getId()));
				fsp.setFlagTuijian("1");
				fsp.setDeleteTag("1");
				fsp.setUserId(user.getId());
				FpShopperProductDTO fspDTO = fpShopperProductService.queryListGetFirst(fsp);
				dto.setFpsDto(fspDTO);
			}
			
			resultMap.setAttribute("detail", dto);
			resultMap.setAttribute("company", companyDTO);
			resultMap.setAttribute("manager", getFpFundManagerDTO(managerList, dto.getJjjlbm()));
			resultMap.setAttribute("manager2", getFpFundManagerDTO(managerList, dto.getJjjlbm2()));
			resultMap.setAttribute("awkwardnessList", awkwardnessList);
			resultMap.setAttribute("buynotice", buynoticeDTO);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query friendshipLink list error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return resultMap;

	}
	
	private FpFundManagerDTO getFpFundManagerDTO(List<FpFundManagerDTO> managerList,String jjjlbm){
		if(managerList != null && !managerList.isEmpty()){
			for(FpFundManagerDTO dto : managerList){
				if(dto.getJjjlbm().equals(jjjlbm)){
					return dto;
				}
			}
		}
		return null;
	}
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
	DecimalFormat df=new DecimalFormat("0.00");
	/**
	 * 
	
	* @Title: queryHs300
	
	* @Description: 查询沪深300数据接口
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/queryHs300")
	@ResponseBody
	public ResultMap queryHs300(HttpServletRequest request,
			HttpServletResponse response) {

		ResultMap resultMap = new ResultMap();
		try{
			String startDate=request.getParameter("startDate");
			String endDate=request.getParameter("endDate");
			String simuProId=request.getParameter("simuProId");
			String regex="\\d{4}-\\d{1,2}-\\d{1,2}";
			//如果参数不符合时间参数返回所有
			if(StringUtils.isBlank(startDate)||!endDate.matches(regex)){
				startDate="";
			}else{
				startDate=sdf.format(sdf.parse(startDate));
			}
			if(StringUtils.isBlank(endDate)||!endDate.matches(regex)){
				endDate="";
			}else{
				 endDate=sdf.format(sdf.parse(endDate));
			}
			//格式转换    to   yyyy-mm-dd
			if(StringUtils.isBlank(startDate)&&StringUtils.isBlank(endDate)){
				Calendar cd=Calendar.getInstance();
				cd.set(Calendar.DATE, cd.get(Calendar.DATE)-1);
				Date start=cd.getTime();
				endDate=sdf.format(start);
				cd.set(Calendar.YEAR,cd.get(Calendar.YEAR)-1);
				Date date=cd.getTime();
				startDate=sdf.format(date);
			}
			try {
				if(!StringUtils.isBlank(simuProId)){
					//累计净值查询 和 过滤
					FpFundInfoDTO dto=new FpFundInfoDTO();
					dto.setId(Integer.parseInt(simuProId));
					String jsonLsjz= fpFundInfoService.fpFpFundInfoLSJZ(dto);
					if(!StringUtils.isBlank(jsonLsjz)){
						jsonLsjz=jsonLsjz.replace("“", "\"");
						JSONArray json=JSONArray.parseArray(jsonLsjz);
						double ljjz=0;
						for (int i = json.size()-1; i>=0; i--) {
							JSONObject j=json.getJSONObject(i);
							if(j==null||StringUtils.isBlank(j.getString("jzrq"))||sdf.parse(j.getString("jzrq")).before(sdf.parse(startDate))||sdf.parse(j.getString("jzrq")).after(sdf.parse(endDate))){
								json.remove(i);
							}
							else{
								if(ljjz==0){
									ljjz= (j.getDouble("ljjz")==null)?0 : j.getDouble("ljjz");
									j.put("zdf", "0%");
								}else{
									try {
										j.put("zdf",df.format((j.getDouble("ljjz")-ljjz)/ljjz*100)+"%");
									} catch (Exception e) {
										log.error("ljjz data error !",e);
									}
								}
							}
						}
						resultMap.setAttribute("listLsjz", json);
						List<HS300DTO> listHS300 =new ArrayList<HS300DTO>();
						if(json.size()>0){
							// 查询沪深300   区间数据
							Map<String, String> hs300Param=new HashMap<String, String>();
							hs300Param.put("startDate", json.getJSONObject(json.size()-1).getString("jzrq"));
							hs300Param.put("endDate", json.getJSONObject(0).getString("jzrq"));
							listHS300 = hs300Service.listHS300(hs300Param);
							//动态计算走势      
							double initzdf=0;
							for (int i = 0; i < listHS300.size(); i++) {
								if(i==0){
									initzdf=Double.parseDouble(listHS300.get(0).getEndPrice());
									listHS300.get(0).setChangePrice("0");
									listHS300.get(0).setChangePriceRate("1");
								}else{
									double endPrice=Double.parseDouble(listHS300.get(i).getEndPrice());
									listHS300.get(i).setChangePrice((endPrice-initzdf)+"");
									listHS300.get(i).setChangePriceRate(df.format(endPrice/initzdf));
								}
							}
						}
						resultMap.setAttribute("list", listHS300);
					}
				}else{
					// 查询沪深300   区间数据
					Map<String, String> hs300Param=new HashMap<String, String>();
					hs300Param.put("startDate", startDate);
					hs300Param.put("endDate", endDate);
					List<HS300DTO> listHS300 = hs300Service.listHS300(hs300Param);
					resultMap.setAttribute("list", listHS300);
					//动态计算走势      
					double initzdf=0;
					for (int i = 0; i < listHS300.size(); i++) {
						if(i==0){
							initzdf=Double.parseDouble(listHS300.get(0).getEndPrice());
							listHS300.get(0).setChangePrice("0");
							listHS300.get(0).setChangePriceRate("1");
						}else{
							double endPrice=Double.parseDouble(listHS300.get(i).getEndPrice());
							listHS300.get(i).setChangePrice((endPrice-initzdf)+"");
							listHS300.get(i).setChangePriceRate(df.format(endPrice/initzdf));
						}
					}
				}
			} catch (Exception e) {
				log.error("listLsjz error !",e);
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			}
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryHs300 error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return resultMap;
	}
	
}